package com.quanyan.assets.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.assets.emun.AssetsErrorEnum;
import com.quanyan.assets.emun.OpType;
import com.quanyan.assets.entity.TbUserEggsAccumulateHistoryExample;
import com.quanyan.assets.entity.vo.AssetsRuleVo;
import com.quanyan.assets.mapper.ETbUserEggsAccumulateHistoryMapper;
import com.quanyan.assets.repository.AccumulateRuleRepository;
import com.quanyan.assets.repository.EggsAccumulateHistoryRepository;
import com.quanyan.assets.service.CurrencyService;
import com.quanyan.assets.service.UtilAssetsRuleService;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * Created by wmb on 2016/6/1.
 */
@Service("utilAssetsRuleService")
public class UtilAssetsRuleServiceImpl implements UtilAssetsRuleService{
    @Autowired
    private CurrencyService currencyService;
    @Autowired
    private ETbUserEggsAccumulateHistoryMapper eTbUserEggsAccumulateHistoryMapper;
    @Autowired
    private EggsAccumulateHistoryRepository egsAccumulateHistoryRepository;
    @Autowired
    private AccumulateRuleRepository accumulateRuleRepository;
    @Override
    public Long getAccumulateByRule(AssetsRuleVo assetsRuleVo) {
        //该规则已使用次数
        int useAmount=accumulateRuleRepository.countUse(assetsRuleVo.getUid(), assetsRuleVo.getSystemCode(), assetsRuleVo.getBusinessCode(),assetsRuleVo.getAssetsType());
        //首次获取固定数值
        if(useAmount==0&&null!=assetsRuleVo.getFirstAmount()&&assetsRuleVo.getFirstAmount().longValue()!=(long)-1){
            return assetsRuleVo.getFirstAmount();
        }
        //使用次数限制
        if(assetsRuleVo.getUseAmount().intValue()!=-1){
            //判断次数是否超过
            if(useAmount>=assetsRuleVo.getUseAmount().byteValue()){
                throw new BizException(AssetsErrorEnum.RULE_NO_TIMES);
            }

        }else if(assetsRuleVo.getTodayUseAmount().intValue()!=-1){
            //非次数使用，今日已使用次数
            int todayUseAmount=accumulateRuleRepository.countUseToday(assetsRuleVo.getUid(), assetsRuleVo.getSystemCode(), assetsRuleVo.getBusinessCode(),assetsRuleVo.getAssetsType());
            if(todayUseAmount>=assetsRuleVo.getTodayUseAmount().byteValue()){
                throw new BizException(AssetsErrorEnum.RULE_NO_TIMES);
            }
        }
        //消费
        if(assetsRuleVo.getOpType()== OpType.CONSUME.id.byteValue()){
            switch (assetsRuleVo.getRuleType()){
                case 1:
                    return Long.parseLong(assetsRuleVo.getAccumulateRule());
                case 2:
                    //消费时需要把相关的业务标识 如订单号
                    if(null==assetsRuleVo.getOrderAmount()){
                        throw new BizException(AssetsErrorEnum.ORDER_AMOUNT_NULL);
                    }
                    //可抵扣的钱
                    BigDecimal money=assetsRuleVo.getOrderAmount().multiply(new BigDecimal(assetsRuleVo.getAccumulateRule()));
                    return money.divide(currencyService.exchangeRatioById(assetsRuleVo.getAssetsType()).getData()).longValue();
                case 4:
                    if(null==assetsRuleVo.getAccumulate()){
                        throw new BizException(AssetsErrorEnum.ACCUMULATE_IS_NULL);
                    }
                    if(assetsRuleVo.getAccumulate()<=0){
                        throw new BizException(AssetsErrorEnum.ACCUMULATE_IS_INVALID);
                    }
                    return assetsRuleVo.getAccumulate();
                default:
                    return 0L;
            }
        }
        else if(assetsRuleVo.getOpType()== OpType.RECEIVE.id.byteValue()){

            switch (assetsRuleVo.getRuleType()){
                case 1:
                    return Long.parseLong(assetsRuleVo.getAccumulateRule());
                case 3:
//                    if(assetsRuleVo.getUid().equals(9003507)){
//                        return new Long(9999);
//                    }
                    return random(assetsRuleVo.getAccumulateRule());
                case 4:
                    if(null==assetsRuleVo.getAccumulate()){
                        if(assetsRuleVo.getBusinessCode().equals("USER_CENTER_RANDOM_EGGS_CODE")){
                            return random("1-0.2,2-0.2,3-0.2,4-0.175,5-0.15,6-0.005,7-0.005,8-0.005,9-0.005,10-0.005,11-0.005,12-0.005,13-0.005,14-0.005,15-0.005,16-0.005,17-0.005,18-0.005,19-0.005,20-0.005");
                        }else{
                            throw new BizException(AssetsErrorEnum.ACCUMULATE_IS_NULL);
                        }
                    }
                    if(assetsRuleVo.getAccumulate()>assetsRuleVo.getMaxUseable()){
                        throw new BizException(AssetsErrorEnum.ACCUMULATE_IS_INVALID);
                    }
                    return assetsRuleVo.getAccumulate();
                default:
                    return 0L;
            }
        }else{
            throw new BizException(ApiResponseEnum.PARAMETER_INVALID);
        }


    }

    //通过概率获取随机鸟蛋数
    private Long random(String accumulateRule) {
//        String str="1-0.2,2-0.2,3-0.2,4-0.175,5-0.15,6-0.005,7-0.005,8-0.005,9-0.005,10-0.005,11-0.005,12-0.005,13-0.005,14-0.005,15-0.005,16-0.005,17-0.005,18-0.005,19-0.005,20-0.005"

        String[] strArr=accumulateRule.split(",");
        BigDecimal random=new BigDecimal(Math.random());
        BigDecimal match=new BigDecimal(0);
        for(int i=0;i<strArr.length;i++){
            if(random.compareTo(match)>=0&&random.compareTo(match.add(new BigDecimal(strArr[i].split("-")[1])))==-1){
                return Long.parseLong(strArr[i].split("-")[0]);
            }
            match=match.add(new BigDecimal(strArr[i].split("-")[1]));
        }

        return 0L;
    }
}
